#include "thread_pool.h"
#include <stdio.h>
#include <QDebug>

using namespace std;

ThreadPool* ThreadPool::Get()
{
    static ThreadPool pool;
    return &pool;
}

void ThreadPool::Init(int pool_size)
{
    for(int i = 0; i < pool_size; i++)
    {
        StreamThread *st = new StreamThread(i);
        st->Start();
        thread_list_.push_back(st);
    }
}

void ThreadPool::AddTask(StreamTask *task)
{
    if(thread_list_.empty())
    {
        qInfo("线程池还未初始化");
        return;
    }
    list<StreamThread*>::iterator min_it = thread_list_.begin();
    for(list<StreamThread*>::iterator it = thread_list_.begin(); it != thread_list_.end(); it++)
    {
        if(min_it == it)
        {
            continue;
        }
        if((*min_it)->TaskSize() > (*it)->TaskSize())
        {
            min_it = it;
        }
    }
    (*min_it)->AddTask(task);
}

void ThreadPool::RemoveTask(StreamTask *task)
{
    for(list<StreamThread*>::iterator it = thread_list_.begin(); it != thread_list_.end(); it++)
    {
        if((*it)->IsContain(task))
        {
            (*it)->RemoveTask(task);
        }
    }
}

void ThreadPool::Destroy()
{
    for(list<StreamThread*>::iterator it = thread_list_.begin(); it != thread_list_.end(); it++)
    {
        StreamThread* st = *it;
        st->Stop();
        delete st;
    }
    thread_list_.clear();
}

ThreadPool::ThreadPool()
{

}
